
package bibliotheque.server;

import bibliotheque.transaction.TransactionId;
import bibliotheque.wave.WaveAction;
import bibliotheque.wave.WaveAgent;

public class ValidateAction extends WaveAction{
    
    private TransactionId id;
    
    
    /** Creates a new instance of ValidateAction */
    public ValidateAction(TransactionId id) {
        this.id = id;
    }
    
    public void PropagateAfter(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.SUBSCRIBING) throw new Exception("Validate failed cause server state is subscribing.");
                if(server.state == Server.State.STARTING) throw new Exception("Validate failed cause server state is starting.");
                if(server.state == Server.State.STOPPING) throw new Exception("Validate failed cause server state is stopping.");
                if(server.state == Server.State.STOP) throw new Exception("Validate failed cause server state is stopped.");
                server.transaction_manager.Validate(this.id);
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
            
        }
    }
    
    public void GlobalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.SUBSCRIBING) throw new Exception("Selection failed cause server state is subscribing.");
                if(server.state == Server.State.STARTING) throw new Exception("Selection failed cause server state is starting.");
                if(server.state == Server.State.STOPPING) throw new Exception("Selection failed cause server state is stopping.");
                if(server.state == Server.State.STOP) throw new Exception("Selection failed cause server state is stopped.");
                
                server.clients.get(this.id.GetClient()).SetValidateResult(true);
            }catch(Exception ex){
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally{
                server.mutex.release();
            }
        }        
    }
}
